/*eslint-disable*/
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import axios from 'axios'
import 'babel-polyfill'
import router from './router'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import {
  Icon
} from 'element-ui';
import {
  Message
} from 'element-ui';
//ElementUtils是为了对话框可移动和拖拽应用的扩展插件
import ElementUtils from 'vue-element-utils';
import VScaleScreen from 'v-scale-screen';
import dataV from '@jiaminghi/data-view'
//import './transfer.js';//实现element-ui对话框拖拽拉伸，由于无法响应曲线自动延伸，启用；
//import VueAwesomeSwiper from 'vue-awesome-swiper'
//import 'swiper/css/swiper.css'
//import echarts from 'echarts'
//设置全局
//ElementUI.Dialog.props['v-el-dialog-drag']=true;
Vue.use(VScaleScreen);
Vue.use(ElementUtils);
Vue.use(ElementUI);
Vue.use(Icon);
Vue.use(dataV);

//Vue.use(QRCode);
//Vue.use(VueAwesomeSwiper);
Vue.prototype.$http = axios;
  function readLocalConfig(){
	axios.get('../../static/addressConfig.json')
	.then((res)=>res.data)
	.then((json)=>{
		//console.log(json);
		Vue.prototype.$baseurl = json.baseAPI.baseurl;
		//下面为webSocket地址
		Vue.prototype.$wssUrl = json.baseAPI.socketUrl;
		Vue.prototype.$http.defaults.baseURL= json.baseAPI.baseurl;
    localStorage.setItem("baseURL",json.baseAPI.baseurl);
    localStorage.setItem("wssurl",json.baseAPI.socketUrl);
	});
}

readLocalConfig();

Vue.prototype.$message = Message;
//Vue.prototype.$message.duration=2000;    //设置提示框默认显示时间为2秒，原为3秒,但是目前不支持，不会生效；

Vue.prototype.$http.defaults.headers.post['Content-Type'] = 'application/json';
Vue.prototype.$http.defaults.headers.common['OS'] = "WEB";
//Vue.prototype.$http.defaults.timeout = 20000;
// Vue.prototype.$baseurl = "http://192.168.0.206:18160/";
// //下面为webSocket地址
// Vue.prototype.$wssUrl = "ws://192.168.0.206:53311/";
// Vue.prototype.$http.defaults.baseURL = "http://192.168.0.206:18160/"; //https://xajdapi.ykiot.net/
//因为token会随时更新，所以不能在这里封装
//Vue.prototype.$http.defaults.headers.token=localStorage.getItem("yktoken");
//Vue.prototype.$listMenus=[];
//表示请求可以携带cookie
//Vue.prototype.$http.defaults.withCredentials=true;
//全局路由改变事件
// router.beforeEach(function(to,from,next){
// 	clearTimeout();
// 	clearInterval();
// 	Message.closeAll();
// 	next();
// })
Vue.prototype.$tableHeaderStyle = {
  'background-color': "#2f4f4f", //#2C3E50
  'color': 'white',
  'fontSize': '0.3rem',
  'height': '0.6rem',
  'line-height': '0.6rem'
};

Vue.prototype.$tableCellStyle = {
  'fontSize': '0.3rem'
};


window.axiosCancel = [];
//设置请求拦截
axios.interceptors.request.use(
  (config) => {
    if (localStorage.getItem("attoken")) {
      config.headers["token"] = localStorage.getItem("attoken");
    }
    //console.log(localStorage.getItem("yktoken"));
    return config;
    // config.cancelToken = new axios.CancelToken(cancel =>{
    // 	window.axiosCancel.push({
    // 		cancel
    // 	})
    // })
  },
  (err) => {
    console.log(err)
  }
);
//设置响应拦截
axios.interceptors.response.use(
  (res) => {
    //console.log(success)
    if (res.data.result == "error") {
      if (res.data.code == 4081) {
        Message.closeAll(); //9月24
        Message.error({
          type: 'error',
          message: '抱歉，登录超时，即将退出，请重新登录!',
          duration: 3000,
          offset: 300,
          center: true
        })
        setTimeout(function() {
          router.push({
            path: '/',
            name: 'Login',
            component: 'Login'
          })
        }, 3000);
        localStorage.clear();
      } else {
        Message.error({
          type: 'error',
          duration: 3000,
          offset: 300,
          message: res.data.msg
        })
      }
      return false;
    }
    return res;
  },
  //(response) => { return response},
  (error) => {
    var zhfive = /^5[0-9]{2}$/;
    var zhfour = /^4[0-9]{2}$/;
    var errStatus = error.response.status;
    if (error.response && errStatus !== 200) {
      Message.closeAll();
      if (zhfour.test(errStatus)) {
        if (errStatus == 404) {
          Message.error({
            type: 'error',
            duration: 2000,
            offset: 300,
            message: '请求的地址不存在！'
          })
        } else {
          Message.error({
            type: 'error',
            duration: 2000,
            offset: 300,
            message: '请求错误！'
          })
        }
      } else if (zhfive.test(errStatus)) {
        Message.error({
          type: 'error',
          duration: 2000,
          offset: 300,
          message: '服务器错误，请与后台人员联系！'
        })
      }
      return false;
    }
    return error;

  })

//Vue.config.productionTip = false 的作用是阻止显示生产模式的消息。
//默认为true，控制台会提示以下信息-----运行的是vue开发模式
Vue.config.productionTip = false;
//以下是三个Vue过滤器
Vue.filter('showTypeFilter', function(type) {
  var show_type = Number(type);
  switch (show_type) {
    case 1:
      return '只读数值';
    case 2:
      return '读写数值';
    case 3:
      return '只读开关';
    case 4:
      return '读写开关';
    case 5:
      return '只读状态(红/绿)';
    case 6:
      return '读写状态';
    case 7:
      return '只读报警(1闪)';
    case 13:
      return '只读报警(0闪)';
    case 15:
      return '只读状态(暗/绿)';
    case 8:
      return '读写报警';

  }
});

Vue.filter('oldTypeFilter', function(type) {
  var oldType = Number(type);
  switch (oldType) {
    case 1:
      return '数值';
    case 2:
      return '开关';
    case 3:
      return '状态(红/绿)';
    case 8:
      return '状态(暗/绿)';
    case 4:
      return '报警(1闪)';
      // case 5:
      //     return '字符串';
    case 7:
      return '报警(0闪)';
    case 6:
      return '多位开关(已停用)';

  }
});

Vue.filter('runMode', function(mode) {
  var runMode = Number(mode);
  switch (runMode) {
    case 1:
      return '边缘采集';
    case 2:
      return '数据透传';
  }
});

Vue.filter('netWay', function(way) {
  var newWay = Number(way);
  switch (newWay) {
    case 1:
      return '4G';
    case 2:
      return 'WiFi';
    case 3:
      return '网口';
    case '':
      return '未知';
  }
});



Vue.filter('appSceneToWord', function(scene) {
  var appScene = Number(scene);
  switch (appScene) {
    case 1:
      return '通用';
    case 2:
      return '水利';
    case 3:
      return '私有协议-A';
    case 5:
      return 'MQTT遥测';

  }
});


Vue.filter('waterMark', function(mark) {
  var markWord = Number(mark);
  switch (markWord) {
    case 0:
      return '瞬时流量';
    case 1:
      return '累计流量';
    case 10:
      return '水位';
    case 20:
      return '室温';
    case 30:
      return '水压';
    case 40:
      return '水温';
    case 51:
      return '水质水温';
    case 52:
      return 'PH值';
    case 53:
      return '溶解氧';
    case 54:
      return '电导率';
    case 55:
      return '浊度';
    case 56:
      return '叶绿素';
    case 57:
      return '蓝绿素';

  }
});

Vue.filter('reportTypeFilter', function(type) {
  var report_type = Number(type);
  switch (report_type) {
    case 0:
      return '设备实时数据(0)';
    case 1:
      return '设备参数数据(1)';
    case 10:
      return '厂商实时数据(10)';
    case 11:
      return '厂商参数数据(11)';
    case 3:
      return '中间变量';
    case 4:
      return '只写数据';
  }
});
Vue.filter('valueTypeFilter', function(type, key) {
  var value_type = Number(type);
  switch (value_type) {
    case 0:
      return '布尔型';
    case 1:
      return '8位有符号';
    case 2:
      return '8位无符号';
    case 3:
      return '16位有符号';
    case 4:
      return '16位无符号';
    case 5:
      return '32位有符号';
    case 6:
      return '32位无符号';
    case 7:
      return '64位有符号';
    case 8:
      return '64位无符号';
    case 9:
      return 'float';
    case 10:
      return 'double';
    case 11:
      return 'SBCD8';
    case 12:
      return 'BCD8';
    case 13:
      return 'SBCD16';
    case 14:
      return 'BCD16';
    case 15:
      return 'SBCD32';
    case 16:
      return 'BCD32';
    case 17:
      return 'SBCD64';
    case 18:
      return 'BCD64';
    case 19:
      return 'string';
      //16位按位
    case 50:
      if (['I', 'Q', 'M', 'V', 'D'].indexOf(key[0]) >= 0) {
        return '8位的第00位';
      } else {
        return '16位的第00位';
      }
    case 51:
      if (['I', 'Q', 'M', 'V', 'D'].indexOf(key[0]) >= 0) {
        return '8位的第01位';
      } else {
        return '16位的第01位';
      }
    case 52:
      if (['I', 'Q', 'M', 'V', 'D'].indexOf(key[0]) >= 0) {
        return '8位的第02位';
      } else {
        return '16位的第02位';
      }
    case 53:
      if (['I', 'Q', 'M', 'V', 'D'].indexOf(key[0]) >= 0) {
        return '8位的第03位';
      } else {
        return '16位的第03位';
      }
    case 54:
      if (['I', 'Q', 'M', 'V', 'D'].indexOf(key[0]) >= 0) {
        return '8位的第04位';
      } else {
        return '16位的第04位';
      }
    case 55:
      if (['I', 'Q', 'M', 'V', 'D'].indexOf(key[0]) >= 0) {
        return '8位的第05位';
      } else {
        return '16位的第05位';
      }
    case 56:
      if (['I', 'Q', 'M', 'V', 'D'].indexOf(key[0]) >= 0) {
        return '8位的第06位';
      } else {
        return '16位的第06位';
      }
    case 57:
      if (['I', 'Q', 'M', 'V', 'D'].indexOf(key[0]) >= 0) {
        return '8位的第07位';
      } else {
        return '16位的第07位';
      }
    case 58:
      return '16位的第08位';
    case 59:
      return '16位的第09位';
    case 60:
      return '16位的第10位';
    case 61:
      return '16位的第11位';
    case 62:
      return '16位的第12位';
    case 63:
      return '16位的第13位';
    case 64:
      return '16位的第14位';
    case 65:
      return '16位的第15位';


  }
});
//过滤器结束


//以下为公共函数；
//token获取函数
var getToken = function() {
  var data = {
    "refresh_token": localStorage.getItem("at_retoken")
  };
  var xhr = new XMLHttpRequest();
  xhr.open('post', Vue.prototype.$baseurl + "api/user/refreshToken", true);
  xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  xhr.send(JSON.stringify(data));
  xhr.timeout = 4000;
  xhr.onreadystatechange = function() {
    // 这步为判断服务器是否正确响应
    if (xhr.readyState == 4 && xhr.status == 200) {
      var res = JSON.parse(xhr.response);
      //console.log(res);
      if (res && res.result == "success") {
        localStorage.setItem("attoken", res.data.accessToken);
      }
    }
  };
};
Vue.prototype.getToken = getToken;
Vue.prototype.allAlarmSocket=null;
Vue.prototype.allAlarmTimer=null;


Vue.filter('protocolPLC', function(value) {
  var oldValue = Number(value);
  switch (oldValue) {
    case 0:
      return 'Fx3';
    case 1:
      return 'Fx2/1';
    default:
      return 'Fx3';


  }
});

Vue.prototype.removeItem = function(arr, val) {
  let index = arr.indexOf(val);
  if (index > -1) {
    arr.splice(index, 1);
  }
  return arr;
};

//协议名称小写转规范写法
Vue.prototype.protocolToUpper = function(str) {
  if (str) {
    var newStr = str.trim();
    switch (newStr) {
      case 'modbus_rtu_master':
        return 'Modbus RTU Master';
      case 'modbus_ascii':
        return 'Modbus Ascii';
        // case 'modbus_rtu_slave':
        // 	return 'Modbus RTU Slave';
      case 'modbus':
        return 'Modbus';
      case 's7_200_ppi':
        return 'S7-200 PPI';
      case 'dl_t645_1997':
        return 'DL/T645-1997';
      case 'dl_t645_2007':
        return 'DL/T645-2007';
      case 'modbus_tcp_client':
        return 'Modbus TCP Client';
      case 'modbus_rtu_over_tcp':
        return 'Modbus RTU Over TCP';
      case 's7_200_smart':
        return 'S7-200 Smart';
      case 's7_200':
        return 'S7-200';
      case 's7_300_400':
        return 'S7-300/400';
      case 's7_1200':
        return 'S7-1200';
      case 's7_1500':
        return 'S7-1500';
      case 'mitsubishi_fx_program':
        return 'Mitsubishi_Fx_Program';
      case 'mitsubishi_fx_serial':
        return 'Mitsubishi_Fx_Serial';

    }
  }
};


//端口名称小写转规范写法
Vue.prototype.channelToUpper = function(string) {
  if (string) {
    let str=string.toLocaleString();
    if (str.indexOf('com') >= 0) {
      return str.toUpperCase();
    } else if (str == 'lora1') {
      return "LoRa1";
    } else if (str == 'lora2') {
      return "LoRa2";
    } else if (str.indexOf('ocal') > 0) {
      return 'Local(内部变量)';
    } else {
      return str.substr(0, 1).toUpperCase() + str.substr(1);
    }

  }
};



Vue.prototype.tampToDate = function(timestamp) {
  var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var Y = date.getFullYear() + '-';
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
  return Y + M + D;
};
Vue.prototype.tampToTime = function(timestamp) {
  var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var Y = date.getFullYear() + '-';
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
  var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
  var m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes()) + ':';
  var s = date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds();
  return Y + M + D + h + m + s;
};
Vue.prototype.getNowTime = function() {
  var a = ["日", "一", "二", "三", "四", "五", "六"];
  var date = new Date(); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var Y = date.getFullYear() + '年';
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '月';
  var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + '日•';
  var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
  var m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes()) + ':';
  var s = date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds();
  var wk = date.getDay();
  var wks = "星期" + a[wk] + "•";
  return Y + M + D + wks + h + m + s;
}
Vue.prototype.getNowTimeObj = function() {
  var a = ["日", "一", "二", "三", "四", "五", "六"];
  var date = new Date(); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var Y = date.getFullYear();
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
  var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
  var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours());
  var m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes());
  var s = date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds();
  var wk = date.getDay();
  var wks = "星期" + a[wk] + "　";
  return {
    year: Y,
    month: M,
    date: D,
    wks: wks,
    hour: h,
    minute: m,
    second: s
  };
};
Vue.prototype.UTC2BeiJ = function(utc_datetime) {
  // 转为正常的时间格式 年-月-日 时:分:秒
  var T_pos = utc_datetime.indexOf('T');
  var Z_pos = utc_datetime.indexOf('.');
  var year_month_day = utc_datetime.substr(0, T_pos);
  var hour_minute_second = utc_datetime.substr(T_pos + 1, Z_pos - T_pos - 1);
  var new_datetime = year_month_day + " " + hour_minute_second; // 2017-03-31 08:02:06

  // 处理成为时间戳
  timestamp = new Date(Date.parse(new_datetime));
  timestamp = timestamp.getTime();
  timestamp = timestamp / 1000;

  // 增加8个小时，北京时间比utc时间多八个时区
  var timestamp = timestamp + 8 * 60 * 60;

  // 时间戳转为时间
  var beijing_datetime = new Date(parseInt(timestamp) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g,
  " ");
  return beijing_datetime; // 2017-03-31 16:02:06
};
Vue.prototype.$getNowFormatDate = function() { //获取当前年月日
  var date = new Date();
  var seperator1 = "-";
  // var seperator2 = ":";
  var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
  var strDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
  var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate

  return currentdate;
};
Vue.prototype.$pickerOptions = {
  //时间包含当天
  shortcuts: [{
      text: '最近三天',
      onClick(picker) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 2);
        picker.$emit('pick', [start, end]);
      }
    },
    {
      text: '最近一周',
      onClick(picker) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
        picker.$emit('pick', [start, end]);
      }
    }, {
      text: '最近十五天',
      onClick(picker) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 14);
        picker.$emit('pick', [start, end]);
      }
    },
    {
      text: '最近二十天',
      onClick(picker) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 19);
        picker.$emit('pick', [start, end]);
      }
    },
    {
      text: '最近一个月',
      onClick(picker) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
        picker.$emit('pick', [start, end]);
      }
    }, {
      text: '最近三个月',
      onClick(picker) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
        picker.$emit('pick', [start, end]);
      }
    }
  ]
};
Vue.prototype.$pickerOptionsSimple = {
  //时间包含当天
  shortcuts: [{
      text: '最近三天',
      onClick(picker) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 2);
        picker.$emit('pick', [start, end]);
      }
    },
    {
      text: '最近一周',
      onClick(picker) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
        picker.$emit('pick', [start, end]);
      }
    }, {
      text: '最近十天',
      onClick(picker) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 9);
        picker.$emit('pick', [start, end]);
      }
    },
    {
      text: '最近十五天',
      onClick(picker) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 14);
        picker.$emit('pick', [start, end]);
      }
    },
    {
      text: '最近二十天',
      onClick(picker) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 19);
        picker.$emit('pick', [start, end]);
      }
    },
    {
      text: '最近一个月',
      onClick(picker) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
        picker.$emit('pick', [start, end]);
      }
    }
  ]
};
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: {
    App
  },
  // data:{
  // 	testAllData:"全局属性"
  // },
  template: '<App/>',
  render: h => h(App)
})

var baseurl = Vue.prototype.$http.defaults.baseURL;
//console.log(baseurl);
export {
  baseurl
};
